#!/usr/bin/env python

import sys
import zmq
from optparse import OptionParser
import logging
impot ConfigParser

import dlibs
import admapi.admincommands
from admapi import Req


logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(levelname)s %(message)s')


def main():
    """docstring for main"""

    usage = "usage: %prog [options] command <command args>"
    opt_parser = OptionParser(usage=usage)
    opt_parser.add_option("-c", "--config", dest="config_file",
            default="/etc/dmq/dmq.ini",
            help=("The path to the config/.ini file for the "
                " Django-dmq instance you wish to administrate."))
    opt_parser.add_option("-m", "--host", dest="host", default=None,
            help=("The hostname of the node you wish to administrate."))
    opt_parser.add_option("-e", "--endpoint", dest="endpoint", default=None,
            help=("The unix socket path of "
                    "the node you wish to administrate."))
    opt_parser.add_option("-p", "--port", dest="port", default=None,
            help=("The port number of the node you wish to administrate."))
    opt_parser.add_option("-t", "--transport", dest="transport", default=None,
            help=("The transport type to use for the node you "
                    "wish to administrate. Options: tcp or ipc"))

    (options, args) = opt_parser.parse_args()
    #print(args)
    #print(options)

    cmd_options = {}
    if len(args) < 1:
        cmd = 'status'
    else:
        cmd = args[0]
        # The user can leave the leading '/' off of the command path.
        # If they do, we'll put it back for them.
        if cmd[0] != '/':
            cmd = "/" + cmd

        cmd_options_ar = args[1:]
        for item in cmd_options_ar:
            k, v = item.split('=', 1)
            cmd_options[k] = v

    if not admapi.admincommands.check_cmd(cmd):
        print("Invalid command, '%s'" % (cmd,))
        opt_parser.print_help()
        sys.exit(1)

    cfgpath = options.config_file

    try:
        cfg = dlibs.get_cfg(cfgpath)
        cfg_section = "DEFAULT"

        unix_socket_dir = cfg.get(cfg_section, 'unix_socket_dir')

        host = options.host or cfg.get(cfg_section, 'zmq_admin_host')
        port = options.port or cfg.getint(cfg_section, 'zmq_admin_port')
        transport = options.transport or cfg.get(cfg_section,
                    'zmq_admin_transport')
        endpoint = options.endpoint or cfg.get(cfg_section,
                    'zmq_admin_unix_socket_dir')

        req = admapi.Req(transport, host=host, port=port, endpoint=endpoint)

        resp = req.send(cmd, cmd_options)
        resp_obj = admapi.decode(resp)
        print("Received : %s" % (resp_obj,))

    except KeyboardInterrupt:
        print("\rCommand canceled by user")
        sys.exit(3)
    except Exception as e:
        opt_parser.print_help()
        import traceback
        traceback.print_exc(e)
        print("\n%s\n" % e)
        sys.exit(2)

    sys.exit(0)
#main()

if __name__ == '__main__':
    main()
